<?php

namespace app\common\command\decrypt;

class Des
{

    /**
     * 加密函数
     * @param string $txt 需加密的字符串
     * @param string $key 加密密钥
     * @return string 加密后的字符串
     */
    public static function jiami($txt)
    {
        $len   = 64;
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
        $nh    = rand(0, $len);
        $ch    = $chars[$nh];
        $mdKey = md5($ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt   = base64_encode($txt);
        $tmp   = '';
        $k     = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % $len;
            $tmp .= $chars[$j];
        }

        return $ch . $tmp;
    }

    /**
     * 解密函数
     * @param string $txt 待解密的字符串
     * @param string $key 解密密钥
     * @return string 解密后的字符串
     */
    public static function jiemi($txt)
    {
        $len = 64;
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
        $ch    = $txt[0];
        $nh    = strpos($chars, $ch);
        $mdKey = md5($ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt   = substr($txt, 1);
        $tmp   = '';
        $k     = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) {
                $j += $len;
            }
            $tmp .= $chars[$j];
        }

        return base64_decode($tmp);
    }

}